package cn.com.dingtek.genius.manager.server.web.controller;


import cn.com.dingtek.genius.manager.server.event.UserOperateEvent;
import cn.com.dingtek.genius.manager.server.repository.db.entity.CompanyBase;
import cn.com.dingtek.genius.manager.server.repository.db.entity.CompanyPush;
import cn.com.dingtek.genius.manager.server.service.CompanyService;
import cn.com.dingtek.genius.manager.server.support.sam.SecurityContextHolder;
import cn.com.dingtek.genius.manager.server.support.sam.annotation.AssertAuth;
import cn.com.dingtek.genius.manager.server.utils.IPUtil;
import cn.com.dingtek.genius.manager.server.web.Result;
import com.alibaba.fastjson.JSONObject;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/company")
public class CompanyController {
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Autowired
    private CompanyService companyService;

    @PostMapping("/list")
    public Result list(@RequestBody JSONObject json) {
        int currentPage = json.getInteger("current_page") == null ? 0 : json.getInteger("current_page");
        int pageSize = json.getInteger("page_size") == null ? 10 : json.getInteger("page_size");
        CompanyBase param = json.getObject("search_param", CompanyBase.class);
        return Result.ok(companyService.list(param, currentPage, pageSize));
    }

    @AssertAuth
    @PostMapping("/add")
    public Result add(@RequestBody JSONObject json, HttpServletRequest request) {
        long userId = SecurityContextHolder.getContext().getToken().getUserId();
        String account = SecurityContextHolder.getContext().getToken().getAccount();

        CompanyBase param = json.toJavaObject(CompanyBase.class);
        try {
            companyService.add(param, DateTime.now().toDate());
            applicationEventPublisher.publishEvent(new UserOperateEvent(this)
                    .setUserId(userId)
                    .setAccountName(account)
                    .setOperateModule("公司管理")
                    .setOperateDesc("新增公司")
                    .setOperateIp(IPUtil.getIpAddress(request))
                    .setLogState(true)
            );
        } catch (Exception e) {
            applicationEventPublisher.publishEvent(new UserOperateEvent(this)
                    .setUserId(userId)
                    .setAccountName(account)
                    .setOperateModule("公司管理")
                    .setOperateDesc("新增公司")
                    .setOperateIp(IPUtil.getIpAddress(request))
                    .setLogState(false)
            );
            throw e;
        }
        return Result.ok();
    }

    @AssertAuth
    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long id) {
        return Result.ok(companyService.info(id));
    }

    @AssertAuth
    @PostMapping("/update")
    public Result update(@RequestBody JSONObject json, HttpServletRequest request) {
        long userId = SecurityContextHolder.getContext().getToken().getUserId();
        String account = SecurityContextHolder.getContext().getToken().getAccount();

        CompanyBase param = json.toJavaObject(CompanyBase.class);
        try {
            companyService.update(param, DateTime.now().toDate());
            applicationEventPublisher.publishEvent(new UserOperateEvent(this)
                    .setUserId(userId)
                    .setAccountName(account)
                    .setOperateModule("公司管理")
                    .setOperateDesc("修改公司")
                    .setOperateIp(IPUtil.getIpAddress(request))
                    .setLogState(true)
            );
        } catch (Exception e) {
            applicationEventPublisher.publishEvent(new UserOperateEvent(this)
                    .setUserId(userId)
                    .setAccountName(account)
                    .setOperateModule("公司管理")
                    .setOperateDesc("修改公司")
                    .setOperateIp(IPUtil.getIpAddress(request))
                    .setLogState(false)
            );
            throw e;
        }
        return Result.ok();
    }

    @AssertAuth
    @GetMapping("/remove/{id}")
    public Result remove(@PathVariable("id") Long id, HttpServletRequest request) {
        long userId = SecurityContextHolder.getContext().getToken().getUserId();
        String account = SecurityContextHolder.getContext().getToken().getAccount();

        try {
            companyService.remove(id);
            applicationEventPublisher.publishEvent(new UserOperateEvent(this)
                    .setUserId(userId)
                    .setAccountName(account)
                    .setOperateModule("公司管理")
                    .setOperateDesc("移除公司")
                    .setOperateIp(IPUtil.getIpAddress(request))
                    .setLogState(true)
            );
        } catch (Exception e) {
            applicationEventPublisher.publishEvent(new UserOperateEvent(this)
                    .setUserId(userId)
                    .setAccountName(account)
                    .setOperateModule("公司管理")
                    .setOperateDesc("移除公司")
                    .setOperateIp(IPUtil.getIpAddress(request))
                    .setLogState(false)
            );
            throw e;
        }
        return Result.ok();
    }

    @AssertAuth
    @GetMapping("/options")
    public Result options() {
        Long currentUserId = SecurityContextHolder.getContext().getToken().getUserId();
        return Result.ok(companyService.options(currentUserId));
    }

    @AssertAuth
    @GetMapping("/push/info/{id}")
    public Result pushInfo(@PathVariable("id") Long id) {
        return Result.ok(companyService.pushInfo(id));
    }

    @AssertAuth
    @PostMapping("/push/info/update")
    public Result pushInfoUpdate(@RequestBody JSONObject json) {
        CompanyPush param = json.toJavaObject(CompanyPush.class);
        companyService.pushInfoUpdate(param, DateTime.now().toDate());
        return Result.ok();
    }


}
